// lib/services/stock_data_service.dart
import 'package:get/get.dart';
import 'package:dio/dio.dart';
import 'package:html/parser.dart' as html_parser;
import '../../data/datasource/local/database.dart';

class StockDataService extends GetxService {
  final Dio _dio = Dio();

  String marketName ="";

  @override
  void onInit() {
    super.onInit();
    // 配置Dio拦截器
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        options.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';
        options.headers['Referer'] = 'https://finance.sina.com.cn';
        return handler.next(options);
      },
    ));
  }

  // 获取股票列表
  Future<List<StockCodesCompanion>> fetchStockList(String market) async {
    try {
      // 获取数据库实例
      final database = Get.find<AppDatabase>();

      switch (market) {
        case 'sh': // 上海A股
          return await _fetchShanghaiStocks(database);
        case 'sz': // 深圳A股
          return await _fetchShenzhenStocks(database);
        case 'cyb': // 创业板
          return await _fetchChiNextStocks(database);
        default:
          return [];
      }
    } catch (e) {
      print('获取股票列表失败: $e');
      // 如果主要方法失败，尝试使用备用方法
      return await _fetchStocksFromEastMoney(market);
    }
  }

  // 获取上海A股列表 - 使用分页获取全部数据
  Future<List<StockCodesCompanion>> _fetchShanghaiStocks(AppDatabase database) async {
    List<StockCodesCompanion> allStocks = [];
    int page = 1;
    const int pageSize = 100; // 每页数量
    bool hasMore = true;

    while (hasMore) {
      try {
        final response = await _dio.get(
          'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData',
          queryParameters: {
            'page': page,
            'num': pageSize,
            'sort': 'symbol',
            'asc': 1,
            'node': 'sh_a',
            '_s_r_a': 'init',
          },
        );

        if (response.statusCode == 200 && response.data is List) {
          final List<dynamic> data = response.data;

          if (data.isEmpty) {
            hasMore = false; // 没有更多数据
            break;
          }

          final pageStocks = data.map((item) {
            final symbol = 'sh${item['code']}';
            final name = item['name']?.toString() ?? '';
            return database.createStockCompanion(symbol, name: name);
          }).toList();

          allStocks.addAll(pageStocks);

          // 如果返回的数据少于请求的数量，说明已经是最后一页
          if (data.length < pageSize) {
            hasMore = false;
          } else {
            page++;
            // 添加延迟以避免请求过于频繁
            await Future.delayed(const Duration(milliseconds: 200));
          }
        } else {
          hasMore = false;
        }
      } catch (e) {
        print('获取上海A股第$page页失败: $e');
        hasMore = false;
      }
    }

    return allStocks;
  }

  // 获取深圳A股列表 - 使用分页获取全部数据
  Future<List<StockCodesCompanion>> _fetchShenzhenStocks(AppDatabase database) async {
    List<StockCodesCompanion> allStocks = [];
    int page = 1;
    const int pageSize = 100;
    bool hasMore = true;

    while (hasMore) {
      try {
        final response = await _dio.get(
          'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData',
          queryParameters: {
            'page': page,
            'num': pageSize,
            'sort': 'symbol',
            'asc': 1,
            'node': 'sz_a',
            '_s_r_a': 'init',
          },
        );

        if (response.statusCode == 200 && response.data is List) {
          final List<dynamic> data = response.data;

          if (data.isEmpty) {
            hasMore = false;
            break;
          }

          final pageStocks = data.map((item) {
            final symbol = 'sz${item['code']}';
            final name = item['name']?.toString() ?? '';
            return database.createStockCompanion(symbol, name: name);
          }).toList();

          allStocks.addAll(pageStocks);

          if (data.length < pageSize) {
            hasMore = false;
          } else {
            page++;
            await Future.delayed(const Duration(milliseconds: 200));
          }
        } else {
          hasMore = false;
        }
      } catch (e) {
        print('获取深圳A股第$page页失败: $e');
        hasMore = false;
      }
    }

    return allStocks;
  }

  // 获取创业板列表 - 使用分页获取全部数据
  Future<List<StockCodesCompanion>> _fetchChiNextStocks(AppDatabase database) async {
    List<StockCodesCompanion> allStocks = [];
    int page = 1;
    const int pageSize = 100;
    bool hasMore = true;

    while (hasMore) {
      try {
        final response = await _dio.get(
          'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData',
          queryParameters: {
            'page': page,
            'num': pageSize,
            'sort': 'symbol',
            'asc': 1,
            'node': 'cyb',
            '_s_r_a': 'init',
          },
        );

        if (response.statusCode == 200 && response.data is List) {
          final List<dynamic> data = response.data;

          if (data.isEmpty) {
            hasMore = false;
            break;
          }

          final pageStocks = data.map((item) {
            final symbol = 'sz${item['code']}'; // 创业板股票代码以sz开头
            final name = item['name']?.toString() ?? '';
            return database.createStockCompanion(symbol, name: name);
          }).toList();

          allStocks.addAll(pageStocks);

          if (data.length < pageSize) {
            hasMore = false;
          } else {
            page++;
            await Future.delayed(const Duration(milliseconds: 200));
          }
        } else {
          hasMore = false;
        }
      } catch (e) {
        print('获取创业板第$page页失败: $e');
        hasMore = false;
      }
    }

    return allStocks;
  }

  // 备用方法：从东方财富网获取股票列表
  Future<List<StockCodesCompanion>> _fetchStocksFromEastMoney(String market) async {
    try {
      final database = Get.find<AppDatabase>();
      String url;
   //  String marketName;

      switch (market) {
        case 'sh':
          url = 'http://quote.eastmoney.com/center/gridlist.html#sh_a_board';
          marketName = '上海A股';
          break;
        case 'sz':
          url = 'http://quote.eastmoney.com/center/gridlist.html#sz_a_board';
          marketName = '深圳A股';
          break;
        case 'cyb':
          url = 'http://quote.eastmoney.com/center/gridlist.html#cyb_board';
          marketName = '创业板';
          break;
        default:
          throw Exception('未知市场类型: $market');
      }

      final response = await _dio.get(url);

      if (response.statusCode == 200) {
        // 解析HTML获取股票列表
        final document = html_parser.parse(response.data);
        final stockElements = document.querySelectorAll('.list-table tbody tr');

        List<StockCodesCompanion> stocks = [];

        for (var element in stockElements) {
          final codeElement = element.querySelector('td:nth-child(2) a');
          final nameElement = element.querySelector('td:nth-child(3) a');

          if (codeElement != null && nameElement != null) {
            final code = codeElement.text.trim();
            final name = nameElement.text.trim();
            final prefix = market == 'sh' ? 'sh' : 'sz';

            stocks.add(database.createStockCompanion('$prefix$code', name: name));
          }
        }

        return stocks;
      } else {
        throw Exception('获取$marketName列表失败: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('从东方财富获取$marketName列表失败: $e');
    }
  }
}